/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import { message, Space, Button, Form, Select } from 'antd';
import ProForm, { ProFormText, ProFormSelect } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import KbAddModal from '@/components/_pages/jdk/registerTable/compontents/KbAddModal';
import KbRemarksModal from '@/components/KbRemarksModal';
import KbRegisterDrawer from '@/components/_pages/jdk/registerTable/compontents/KbRegisterDrawer';
import KbSetPriceModal from '@/components/_pages/jdk/registerTable/compontents/KbSetPriceModal';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ConnectState } from '@/models/connect';
import type { REGISTER_COLUMNS, FormData } from '@/components/_pages/jdk/index.d';
import {
  deliveryCountOptions,
  registerColumns,
  issuedYesterdayOptions,
  sourceOptions,
} from '@/components/_pages/jdk/index.config';
import { getRegisterList } from '@/services/jdk/register';
import { usePageTabsChange } from '@/utils/hooks/pageTabs';
import KeepAlive from '@base/components/keep-alive';
import { usePaginationCache } from '@base/components/keep-alive/_utils';
import { useSelector, history } from 'umi';
import styles from './index.less';
import CityCascader from '@base/components/cityCascader';

// interface SearchData {
//   phone?: string;
//   league_phone?: string;
//   league_name?: string;
//   address?: {
//     province?: string;
//     city?: string;
//   };
// }

const Index = () => {
  const defaultValues = {
    address_ids: null,
    type: 'phone',
    delivery_count_type: 'day_1',
    is_order: '',
    val: '',
    source_type: '',
  };
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const formDataRef = useRef<any>(null);
  const [show] = usePageTabsChange();
  const [rowKeys, setRowKeys] = useState<any[]>([]);
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const [visible, setVisible] = useState<boolean>(false);
  const [record, setRecord] = useState<any>(false);
  const [remarkVisible, setRemarkVisible] = useState<boolean>(false);
  const [modalProps, setModalProps] = useState<any>({ setPriceVisible: false });
  const onCancel = () => setVisible(false);

  const handleOption = (record_: any) => {
    setRecord(record_);
    setRemarkVisible(true);
  };

  const handleDetail = (record_: any) => {
    const { user_id } = record_;
    history.push({ pathname: '/f/jdk/appRegister/details', query: { user_id } });
  };

  const optionColumns: ProColumns<REGISTER_COLUMNS>[] = [
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      width: winSize === 'xs' ? 120 : 150,
      render: (_, record_) => {
        return (
          <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
            <a key='detail' onClick={handleDetail.bind(null, record_)}>
              详情
            </a>
            <a key='remark' onClick={handleOption.bind(null, record_)}>
              备注
            </a>
          </Space>
        );
      },
    },
  ];

  const recordFormData = (param: FormData) => {
    const { type, val, is_order, delivery_count_type, address_ids, source_type } = param as any;
    const data = {
      is_order,
      delivery_count_type,
      [type]: val,
      address: address_ids
        ? {
            province: address_ids[0],
            city: address_ids[1],
          }
        : {},
    };
    if (source_type) {
      data.source_type = source_type;
    }
    formDataRef.current = data;
  };

  const requestTableData = async (values: any) => {
    const { current: page } = values;
    delete values.current;
    if (!formDataRef.current) {
      recordFormData(formRef.current?.getFieldsValue());
    }
    const { code, data, msg } = await getRegisterList({ page, ...values, ...formDataRef.current });
    if (code == 0) {
      return { data: data.list, total: data.total };
    } else {
      message.error(msg);
      return {};
    }
  };

  const onSubmit = async (param: FormData) => {
    recordFormData(param);
    actionRef.current?.reload(true);
  };

  const handleChange = (keys: any) => setRowKeys(keys);

  const onCancelModal = () => {
    setRowKeys([]);
    setModalProps({
      rowKeys: [],
      setPriceVisible: false,
    });
  };

  const handleOpenModal = () => {
    if (!rowKeys.length) {
      message.error('批量设置请至少选择一项');
      return;
    }
    setModalProps({
      rowKeys,
      setPriceVisible: true,
    });
  };

  useEffect(() => {
    if (show) actionRef.current?.reload();
  }, [show]);

  const pagination = usePaginationCache('table', {
    pageSize: 20,
    showQuickJumper: false,
    showSizeChanger: false,
  });

  const { Option } = Select;
  const prefixSelector = (
    <Form.Item name='type' noStyle>
      <Select style={{ width: 140 }}>
        <Option value='phone'>商户手机号</Option>
        <Option value='league_phone'>加盟商手机号</Option>
        <Option value='league_name'>加盟商名称</Option>
        <Option value='shop_name'>商家名称</Option>
      </Select>
    </Form.Item>
  );
  return (
    <PageContainer className={styles.main} title={false}>
      <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
        <KeepAlive cacheId='form'>
          <ProForm
            formRef={formRef}
            layout='inline'
            onFinish={onSubmit}
            initialValues={defaultValues}
            submitter={{
              render: (form_props) => {
                return [
                  <Button
                    loading={false}
                    type='primary'
                    key='submit'
                    onClick={() => form_props.form?.submit?.()}
                  >
                    查询
                  </Button>,
                  <Button
                    loading={false}
                    key='reseat'
                    onClick={() => {
                      form_props.form?.setFieldsValue(defaultValues);
                      form_props.form?.submit?.();
                    }}
                  >
                    重置
                  </Button>,
                  <Space key='set'>
                    <Button type='primary' onClick={handleOpenModal}>
                      批量设置运力价格
                    </Button>
                    <KbRegisterDrawer winSize={winSize} actionRef={actionRef}>
                      <Button type='primary'>一键注册</Button>
                    </KbRegisterDrawer>
                  </Space>,
                ];
              },
            }}
          >
            <Form.Item label='商家地址' name='address_ids'>
              <CityCascader fullName style={{ width: 100 }} type='city' />
            </Form.Item>
            <ProFormSelect
              allowClear={false}
              options={deliveryCountOptions}
              name='delivery_count_type'
              label='发单量'
            />
            <ProFormSelect
              allowClear={false}
              options={issuedYesterdayOptions}
              name='is_order'
              label='昨日是否发单'
            />
            <ProFormText
              label='类型'
              name='val'
              addonBefore={prefixSelector}
              fieldProps={{
                style: { width: 200 },
              }}
            />
            <ProFormSelect
              allowClear={false}
              options={sourceOptions}
              name='source_type'
              label='来源'
            />
          </ProForm>
        </KeepAlive>
      </Space>
      <DragTable>
        <ProTable<REGISTER_COLUMNS>
          rowKey='user_id'
          actionRef={actionRef}
          request={requestTableData}
          columns={[...registerColumns(), ...optionColumns]}
          search={false}
          options={false}
          pagination={pagination}
          rowSelection={{
            type: 'checkbox',
            selectedRowKeys: rowKeys,
            onChange: handleChange,
            preserveSelectedRowKeys: true,
          }}
          scroll={{ x: 960 }}
        />
        <KbAddModal visible={visible} userId={'11'} onCancel={onCancel} />
      </DragTable>
      <KbRemarksModal
        modalTitle={`添加备注 ｜ ${record.phone}`}
        required
        visible={remarkVisible}
        setVisible={setRemarkVisible}
        formatDataMap={{
          label: 'operate_name',
          remark: 'remark',
          user: 'operate_phone',
          time: 'create_time',
        }}
        api='/jdk/League/remark'
        formData={{ user_id: record.user_id }}
        listApi='/jdk/League/getRemarkList'
        listFormData={{ user_id: record.user_id }}
      />
      <KbSetPriceModal tableRef={actionRef} {...modalProps} onCancelModal={onCancelModal} />
    </PageContainer>
  );
};

export default Index;
